package com.cloud.class04.controller;

import com.cloud.class04.entities.Pay;
import com.cloud.class04.entities.PayDTO;
import com.cloud.class04.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassDescription:
 * @JdkVersion: 17
 * @Author: yxy
 * @Created: 2024/4/10 10:38
 */
@RestController
public class OrderController {
    //    public static final String PaymentSrv_URL = "http://localhost:8001";
    //服务注册中心上的微服务名称
    public static final String PaymentSrv_URL = "http://cloud-payment-service";
    @Resource
    private RestTemplate restTemplate;

    /* 一般情况下，通过浏览器的地址栏输入url，发送的只能是get请求
     * 我们底层调用的是post方法，模拟消费者发送get请求，客户端消费者
     * 参数可以不添加@RequestBody
     * @param payDTO
     * @return
     */
    @GetMapping("/consumer/pay/add")
    public ResultData addOrder(PayDTO payDTO) {
//        http://localhost:8001/pay/add
        return restTemplate.
                postForObject(PaymentSrv_URL + "/pay/add",
                        payDTO, ResultData.class);
    }

    // 删除+修改操作作为家庭作业，O(∩_∩)O。。。。。。。
    @GetMapping("/consumer/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/" + id, ResultData.class, id);
    }


    @DeleteMapping("/consumer/pay/del/{id}")
//    @PathVariable作用是将请求路径中的路径上参数映射到形参中
    public ResultData deletePay(@PathVariable("id") Integer id) {

        // 使用 exchange 方法替代 delete 方法，并指定期望的响应类型为 ResponseEntity<ResultData>
        ResponseEntity<ResultData> response = restTemplate.exchange(
                PaymentSrv_URL + "/pay/del/" + id,
                HttpMethod.DELETE,
                null, // 请求体可以为空
                ResultData.class // 期望的响应类型
        );

        // 处理响应，返回响应体内容
        return response.getBody();
    }

//    @PatchMapping("/consumer/pay/update")
////    @PathVariable作用是将请求路径中的路径上参数映射到形参中
//    public ResultData updatePay(@RequestBody PayDTO payDTO) {
//        return restTemplate.
//                patchForObject(PaymentSrv_URL + "/pay/update", payDTO, ResultData.class);
////        restTemplate.put(PaymentSrv_URL + "/pay/update", payDTO, ResultData.class);
//
//    }


    @PutMapping("/consumer/pay/update")
    public ResultData updatePay(@RequestBody PayDTO payDTO) {
        //put
//        restTemplate.put(PaymentSrv_URL + "/pay/update", payDTO, ResultData.class);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Custom-Header", "value");

        HttpEntity<PayDTO> requestEntity = new HttpEntity<>(payDTO, headers);

        // 添加查询参数（如果需要）
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(PaymentSrv_URL + "/pay/update")
                .queryParam("paramName", "paramValue");

        return restTemplate.exchange(
                builder.toUriString(),
                HttpMethod.PUT,
                requestEntity,
                ResultData.class
        ).getBody();
    }

    @GetMapping("/consumer/pay/getall")
//    @PathVariable作用是将请求路径中的路径上参数映射到形参中
    public ResultData<List<Pay>> getAll() {
        return restTemplate.
                getForObject(PaymentSrv_URL + "/pay/getall", ResultData.class);


    }


    @GetMapping(value = "/consumer/pay/get/info")
    private String getInfoByConsul() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/info", String.class);
    }

    @Resource
    public DiscoveryClient discoveryClient;

    @GetMapping(value = "/consumer/discovery")
    public List<Map<String, String>> discovery() {
        List<ServiceInstance> services = discoveryClient.getInstances("cloud-payment-service");
        List<Map<String, String>> list = new ArrayList<>();
        for (ServiceInstance service : services) {
            System.out.println("实例名为" + service.getInstanceId() + "ip:" + service.getHost()
                    + "端口为：" + service.getPort() + "请求资源名为：" + service.getUri());
            Map map = new HashMap<>();
            map.put("实例名", service.getInstanceId());
            map.put("ip", service.getHost());
            map.put("端口", service.getPort());
            map.put("请求资源名", service.getUri());
            list.add(map);
        }
        return list;

    }
}
